#!/bin/bash

NUMBER=
ACTION=

function makefile {
    if [ ! -d "${NUMBER}" ]
    then
        echo "Error: exam directory not exists!"
        exit 1
    fi
    ./template.sh -m -n "${NUMBER}" > "${NUMBER}"/Makefile;
}

function csource {
    if [ ! -d "${NUMBER}" ]; then
        echo "Error: exam directory not exists!"
        exit 1
    fi
    ./template.sh -c -n "${NUMBER}" > "${NUMBER}"/"${NUMBER}".c;
}

function gitignore {
    if [ ! -d "${NUMBER}" ]; then
        echo "Error: exam directory not exists!"
        exit 1
    fi
    ./template.sh -g -n "${NUMBER}" > "${NUMBER}"/.gitignore;
}

function scaffold {
    if [ -d "${NUMBER}" ]
    then
        echo "Error: exam directory exists!"
        exit 1
    fi
    mkdir "${NUMBER}";
    makefile;
    csource;
    gitignore;
}

function usage {
    echo "Usage:"
    echo " -h             Show this message and quit"
    echo " -n             Specify the question number"
    echo " -m             Generate Makefile template,"
    echo "                    and replace the original if it exists"
    echo " -g             Generate gitignore template,"
    echo "                    and replace the original if it exists"
    echo " -s             Gererate the scaffold directory"
    exit 0
}

while getopts :hn:mgs opt; do
    case ${opt} in
        h)
            usage
            ;;
        n)
            [[ x"$NUMBER" != x"" ]] && echo "Multiple number specified."
            NUMBER="${OPTARG}"
            ;;
        m)
            [[ x"${ACTION}" != x"" ]] && echo "Multiple action specified."
            ACTION=makefile
            ;;
        g)
            [[ x"${ACTION}" != x"" ]] && echo "Multiple action specified."
            ACTION=gitignore
            ;;
        s)
            [[ x"${ACTION}" != x"" ]] && echo "Multiple action specified."
            ACTION=scaffold
            ;;
        *)
            printf 'Invalid Option: %s.\n' "$1"
            usage
            ;;
     esac
done

case ${ACTION} in
    makefile)
        [[ "$NUMBER" == "" ]] && echo "No question number specified." && exit 1;
        makefile;
        ;;
    gitignore)
        [[ "$NUMBER" == "" ]] && echo "No question number specified." && exit 1;
        gitignore;
        ;;
    scaffold)
        [[ "$NUMBER" == "" ]] && echo "No question number specified." && exit 1;
        scaffold;
        ;;
    *)
        echo "No action specified.";
        exit 1;
        ;;
esac
